import logging
import logging.handlers
import os
import pdb
import pwd
import re
import sys
import time

# ---------------------------------------------------------------------------
def autofs_to_ccs(path):
    """
    Change paths from, eg., "/autofs/na1_home/tpb/prj" to "/ccs/home/tpb/prj"
    """
    return re.sub('/autofs/na\d+_', '/ccs/', path)

# ---------------------------------------------------------------------------
def contents(filepath, string=True):
    """
    Return the contents of a file as a string.
    """
    f = open(filepath, 'r')
    if string:
        rval = "".join(f.readlines())
    else:
        rval = f.readlines()
    f.close()
    return rval

# ---------------------------------------------------------------------------
def get_reqdir_name(landing_pad, username):
    """
    Return a directory name of the form <landing_pad>/<user>.YYYY.mmdd.HHMMSS
    """
    now = time.strftime("%Y.%m%d.%H%M%S")
    rval = "%s/%s.%s" % (landing_pad, username, now)
    return rval

# ---------------------------------------------------------------------------
def has_java_exception(longstr):
    """
    Return True if longstr contains a Java exception, otherwise False.
    """
    exception_signature = "Exception(: | in )"
    q = re.findall(exception_signature, longstr)
    return(q != [])

# ---------------------------------------------------------------------------
def lograise(msg):
    """
    Log a message and then use it to raise an exception
    """
    log = simple_logger()
    log.error(msg)
    raise StandardError(msg)

# ---------------------------------------------------------------------------
def my_name():
    """
    Return the caller's function name.
    """
    return sys._getframe(1).f_code.co_name

# ---------------------------------------------------------------------------
def install_dir():
    """
    Return the grandparent of the directory I was launched from.
    Should be equal to $SCIGEST_HOME for things to work correctly.
    """
    launch_dir = autofs_to_ccs(os.path.abspath(sys.modules[__name__].__file__))
    return os.path.dirname(os.path.dirname(launch_dir))
    
# ---------------------------------------------------------------------------
def require_dot_scigest():
    """
    Ensure that directory $HOME/.scigest exists. If not create it. If
    it already does, return without doing anything. If it exists but
    is not a directory, raise an exception
    """
    dirname = "%s/.scigest" % user_home()
    if not os.path.exists(dirname):
        os.mkdir(dirname)
    if not os.path.isdir(dirname):
        raise StandardError("%s/.scigest exists but is not a directory"
                            % user_home())

    if not os.path.exists("%s/output/1" % dirname):
        os.makedirs("%s/output/1" % dirname)
    
# ---------------------------------------------------------------------------
def scigest_home():
    """
    Return the value of the environment variable $SCIGEST_HOME. If it
    is not set, die with an error.
    """
    rval = os.getenv("SCIGEST_HOME")
    if (None == rval or rval != install_dir()):
        raise StandardError("Please set $SCIGEST_HOME to '%s' and try again"
                            % install_dir())
    return rval

# ---------------------------------------------------------------------------
def simple_logger():
    # logging.basicConfig(filename="/tmp/ezpub.log", level=logging.DEBUG)
    simple_logger.logfile = "/tmp/ezpub.log"
    simple_logger.level = logging.DEBUG

    try:
        return simple_logger.logger
    except:
        simple_logger.logger = logging.getLogger("ezpub")
        simple_logger.logger.setLevel(simple_logger.level)
        # ch = logging.StreamHandler()
        # ch.setLevel(simple_logger.level)
        fh = logging.handlers.RotatingFileHandler(simple_logger.logfile,
                                                  maxBytes = 10*1024*1024,
                                                  backupCount = 5)
        fh.setLevel(simple_logger.level)
        fmt = logging.Formatter("%(asctime)s:%(levelname)s - %(message)s")
        fh.setFormatter(fmt)
        simple_logger.logger.addHandler(fh)
        return simple_logger.logger

# ---------------------------------------------------------------------------
def supported_metadata_filenames():
    """
    Return a list of the supported filenames for external metadata.
    """
    return ["readme.md", "readme.txt", "readme.html"]

# ---------------------------------------------------------------------------
def user_home():
    """
    Return the value of the environment variable $HOME. If it is not
    set, die with an error.
    """
    rval = os.getenv("HOME")
    if (None == rval):
        raise StandardError("Please set $HOME and try again")
    return rval

# ---------------------------------------------------------------------------
def username():
    """
    Look up and return the current username
    """
    return pwd.getpwuid(os.getuid()).pw_name

# ---------------------------------------------------------------------------
def verbose_rm(filepath, dryrun=False):
    """
    Check whether a file exists. If so, announce that it is being
    removed, and remove it.
    """
    rval = 0
    if os.path.exists(filepath):
        rval = 1
        print("rm %s" % filepath)
        if not dryrun:
            os.unlink(filepath)
    return rval

# ---------------------------------------------------------------------------
def verbose_rmdir(dpath, dryrun=False):
    """
    Check whether a directory exists. If so, announce that it is being
    removed, and remove it. The caller is responsible for ensuring
    that the directory is empty and can be removed.
    """
    rval = 0
    if os.path.isdir(dpath):
        rval = 1
        print("rmdir %s" % dpath)
        if not dryrun:
            os.rmdir(dpath)
    return rval
